// 修改后的DocumentGenerationService.java
package com.mobile.service.impl;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.mobile.service.dao.DaoSupport;
import com.mobile.service.dto.WorkOrderDTO;
import com.mobile.service.entity.BusinessDocument;
import com.mobile.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文档生成服务
 * 用于生成业务处理结果文书，如受理通知书、不予受理决定书等
 */
@Service
public class DocumentGenerationService {

    private static final Logger logger = LoggerFactory.getLogger(DocumentGenerationService.class);

    @Autowired
    private DocumentStorageService documentStorageService;

    // 文书类型常量
    private static final String PENSION_ACCEPTANCE = "养老保险申报受理通知书";
    private static final String PENSION_REJECTION = "养老保险申报不予受理决定书";
    private static final String WORK_INJURY_ACCEPTANCE = "工伤保险申报受理通知书";
    private static final String WORK_INJURY_REJECTION = "工伤保险申报不予受理决定书";
    private static final String UNEMPLOYMENT_ACCEPTANCE = "失业保险申报受理通知书";
    private static final String UNEMPLOYMENT_REJECTION = "失业保险申报不予受理决定书";

    private static final String BUSINESS_PENSION = "养老保险";
    private static final String BUSINESS_WORK_INJURY = "工伤保险";
    private static final String BUSINESS_UNEMPLOYMENT = "失业保险";

    private static final String RESULT_ACCEPTED = "COMPLETED";
    private static final String RESULT_REJECTED = "REJECTED";

    /**
     * 生成业务处理结果文书PDF并保存到服务器
     * @param workOrderDTO 工单信息
     * @return 保存的文书信息
     */
    public BusinessDocument generateAndSaveBusinessDocument(WorkOrderDTO workOrderDTO) {
        String businessType = workOrderDTO.getInsuranceType();
        String result = workOrderDTO.getAllocationStatus();
        try {
            // 确定文书类型
            String documentType = determineDocumentType(businessType, result);

            // 生成PDF文档
            byte[] pdfContent = createPdfDocument(workOrderDTO, businessType, result, documentType);

            // 生成文件名
            String fileName = generateFileName(businessType, result);

            // 保存文书到服务器
            BusinessDocument document = documentStorageService.saveDocument(
                    workOrderDTO.getWorkOrderId(), businessType, result, pdfContent, fileName, documentType);

            logger.info("成功生成并保存文书: {}", fileName);
            return document;
        } catch (Exception e) {
            logger.error("生成并保存文书失败，工单ID: {}，业务类型: {}，结果: {}",
                    workOrderDTO.getWorkOrderId(), businessType, result, e);
            throw new RuntimeException("文书生成失败", e);
        }
    }

    /**
     * 创建PDF文档
     * @param workOrderDTO 工单信息
     * @param businessType 业务类型
     * @param result 处理结果
     * @param documentType 文书类型
     * @return PDF字节数组
     */
    private byte[] createPdfDocument(WorkOrderDTO workOrderDTO, String businessType, String result, String documentType) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 创建文档
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, baos);

        document.open();

        // 设置中文字体
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font titleFont = new Font(bfChinese, 16, Font.BOLD);
        Font headerFont = new Font(bfChinese, 12, Font.NORMAL);
        Font contentFont = new Font(bfChinese, 10, Font.NORMAL);

        // 添加标题
        Paragraph title = new Paragraph(documentType, titleFont);
        title.setAlignment(Element.ALIGN_CENTER);
        title.setSpacingAfter(20);
        document.add(title);

        // 添加文书编号
        Paragraph documentNumber = new Paragraph("编号: " + generateDocumentNumber(businessType), contentFont);
        documentNumber.setAlignment(Element.ALIGN_RIGHT);
        documentNumber.setSpacingAfter(20);
        document.add(documentNumber);

        // 添加表格形式的内容
        PdfPTable table = new PdfPTable(2);
        table.setWidthPercentage(100);
        table.setSpacingBefore(10f);
        table.setSpacingAfter(10f);

        float[] columnWidths = {1f, 2f};
        table.setWidths(columnWidths);

        // 申请人信息
        addTableRow(table, "申请人", getApplicantName(workOrderDTO), headerFont, contentFont);
        addTableRow(table, "身份证号", maskIdNumber(getApplicantId(workOrderDTO)), headerFont, contentFont);
        addTableRow(table, "申请日期", formatDate(workOrderDTO.getCreateDatetime()), headerFont, contentFont);
        addTableRow(table, "业务类型", getBusinessTypeName(businessType), headerFont, contentFont);
        addTableRow(table, "紧急程度", workOrderDTO.getUrgencyLevel() != null ? workOrderDTO.getUrgencyLevel() : "", headerFont, contentFont);
        addTableRow(table, "业务属地", workOrderDTO.getBusinessLocation() != null ? workOrderDTO.getBusinessLocation() : "", headerFont, contentFont);
        addTableRow(table, "处理结果", getResultDescription(result), headerFont, contentFont);
        addTableRow(table, "处理日期", formatDate(new Date()), headerFont, contentFont);

        document.add(table);

        // 处理意见
        Paragraph opinionTitle = new Paragraph("处理意见:", headerFont);
        opinionTitle.setSpacingBefore(20);
        document.add(opinionTitle);

        Paragraph opinionContent;
        if (RESULT_ACCEPTED.equals(result)) {
            opinionContent = new Paragraph("经审核，您提交的申请材料齐全，符合受理条件，现予受理。\n\n" +
                    "注意事项: 请关注后续审核进度，如有疑问可联系相关工作人员。", contentFont);
        } else {
            opinionContent = new Paragraph("经审核，您提交的申请材料不符合受理条件，现不予受理。\n" +
                    "不予受理原因: 材料不齐全或不符合相关规定。\n\n" +
                    "救济途径: 如对本决定有异议，可在收到本通知书之日起60日内向上级部门申请行政复议。", contentFont);
        }
        opinionContent.setSpacingBefore(10);
        opinionContent.setSpacingAfter(30);
        document.add(opinionContent);

        // 落款
        Paragraph authority = new Paragraph(getAuthorityName(businessType), contentFont);
        authority.setAlignment(Element.ALIGN_RIGHT);
        document.add(authority);

        Paragraph date = new Paragraph(formatDate(new Date()), contentFont);
        date.setAlignment(Element.ALIGN_RIGHT);
        date.setSpacingAfter(30);
        document.add(date);

        document.close();
        writer.close();
        return baos.toByteArray();
    }

    /**
     * 添加表格行
     */
    private void addTableRow(PdfPTable table, String header, String content, Font headerFont, Font contentFont) {
        PdfPCell headerCell = new PdfPCell(new Phrase(header, headerFont));
        headerCell.setBorder(Rectangle.BOX);
        headerCell.setPadding(5);
        table.addCell(headerCell);

        PdfPCell contentCell = new PdfPCell(new Phrase(content != null ? content : "", contentFont));
        contentCell.setBorder(Rectangle.BOX);
        contentCell.setPadding(5);
        table.addCell(contentCell);
    }

    /**
     * 确定文书类型
     * @param businessType 业务类型
     * @param result 处理结果
     * @return 文书类型描述
     */
    private String determineDocumentType(String businessType, String result) {
        if (RESULT_ACCEPTED.equals(result)) {
            switch (businessType) {
                case BUSINESS_PENSION:
                    return PENSION_ACCEPTANCE;
                case BUSINESS_WORK_INJURY:
                    return WORK_INJURY_ACCEPTANCE;
                case BUSINESS_UNEMPLOYMENT:
                    return UNEMPLOYMENT_ACCEPTANCE;
                default:
                    throw new IllegalArgumentException("不支持的业务类型: " + businessType);
            }
        } else if (RESULT_REJECTED.equals(result)) {
            switch (businessType) {
                case BUSINESS_PENSION:
                    return PENSION_REJECTION;
                case BUSINESS_WORK_INJURY:
                    return WORK_INJURY_REJECTION;
                case BUSINESS_UNEMPLOYMENT:
                    return UNEMPLOYMENT_REJECTION;
                default:
                    throw new IllegalArgumentException("不支持的业务类型: " + businessType);
            }
        } else {
            throw new IllegalArgumentException("不支持的处理结果: " + result);
        }
    }

    /**
     * 生成文书编号
     * @param businessType 业务类型
     * @return 文书编号
     */
    private String generateDocumentNumber(String businessType) {
        String prefix = "";
        switch (businessType) {
            case BUSINESS_PENSION:
                prefix = "YL";
                break;
            case BUSINESS_WORK_INJURY:
                prefix = "GS";
                break;
            case BUSINESS_UNEMPLOYMENT:
                prefix = "SY";
                break;
            default:
                prefix = "YW";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        int randomNum = (int) (Math.random() * 9000) + 1000; // 生成1000-9999的随机数

        return prefix + dateStr + randomNum;
    }

    /**
     * 生成文件名
     * @param businessType 业务类型
     * @param result 处理结果
     * @return 文件名
     */
    private String generateFileName(String businessType, String result) {
        String businessName = getBusinessTypeName(businessType);
        String resultName = RESULT_ACCEPTED.equals(result) ? "受理通知书" : "不予受理决定书";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sdf.format(new Date());

        return businessName + resultName + "_" + timestamp + ".pdf";
    }

    /**
     * 获取业务类型名称
     * @param businessType 业务类型代码
     * @return 业务类型名称
     */
    private String getBusinessTypeName(String businessType) {
        switch (businessType) {
            case BUSINESS_PENSION:
                return "养老保险";
            case BUSINESS_WORK_INJURY:
                return "工伤保险";
            case BUSINESS_UNEMPLOYMENT:
                return "失业保险";
            default:
                return "社会保险";
        }
    }

    /**
     * 获取处理结果描述
     * @param result 结果代码
     * @return 结果描述
     */
    private String getResultDescription(String result) {
        return RESULT_ACCEPTED.equals(result) ? "受理" : "不予受理";
    }

    /**
     * 获取申请人姓名（模拟）
     * @param workOrderDTO 工单信息
     * @return 申请人姓名
     */
    private String getApplicantName(WorkOrderDTO workOrderDTO) {
        // 实际项目中应该从申请人ID查询获取姓名
        return "张三"; // 模拟数据
    }

    /**
     * 获取申请人ID
     * @param workOrderDTO 工单信息
     * @return 申请人ID
     */
    private String getApplicantId(WorkOrderDTO workOrderDTO) {
        return workOrderDTO.getApplicantId() != null ? workOrderDTO.getApplicantId() : "";
    }

    /**
     * 隐藏身份证号中间部分
     * @param idNumber 身份证号
     * @return 隐藏后的身份证号
     */
    private String maskIdNumber(String idNumber) {
        if (StringUtil.isEmpty(idNumber) || idNumber.length() < 8) {
            return idNumber;
        }
        return idNumber.substring(0, 6) + "********" + idNumber.substring(idNumber.length() - 4);
    }

    /**
     * 获取机构名称
     * @param businessType 业务类型
     * @return 机构名称
     */
    private String getAuthorityName(String businessType) {
        switch (businessType) {
            case BUSINESS_PENSION:
                return "XX市养老保险管理中心";
            case BUSINESS_WORK_INJURY:
                return "XX市工伤保险管理中心";
            case BUSINESS_UNEMPLOYMENT:
                return "XX市失业保险管理中心";
            default:
                return "XX市社会保险管理中心";
        }
    }

    /**
     * 格式化日期
     * @param date 日期
     * @return 格式化后的日期字符串
     */
    private String formatDate(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(date);
    }
}
